package com.fdb.efp.console.api.rest;

import com.irdstudio.basic.framework.core.bean.KeyValue;
import com.irdstudio.basic.framework.core.constant.*;
import com.irdstudio.basic.framework.core.util.BeanUtility;
import com.irdstudio.basic.framework.core.util.SpringContextUtils;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.core.vo.UserInfo;
import com.irdstudio.basic.framework.web.controller.AbstractController;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.facade.PatternedLimitableSeqService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.*;
import com.irdstudio.efp.console.service.vo.*;
import com.irdstudio.efp.e4a.service.facade.SRoleDataRuleService;
import com.irdstudio.efp.e4a.service.facade.SRuleCollService;
import com.irdstudio.efp.e4a.service.vo.SRuleCollVO;
import com.irdstudio.efp.flow.service.facade.BizFlowInfoService;
//import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.flow.service.vo.BizFlowInfoVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api")
public class PrdInfoApplyController extends AbstractController {

	@Autowired
	@Qualifier("prdInfoApplyService")
	private PrdInfoApplyService prdInfoApplyService;
	@Autowired
	@Qualifier("prdInfoService")
	private PrdInfoService prdInfoService;
//	@Autowired
//	@Qualifier("flowUrlConfigService")
//	private FlowUrlConfigService flowUrlConfigService;
	@Autowired
	@Qualifier("bizFlowInfoService")
	private BizFlowInfoService bizFlowInfoService;
	@Autowired
	@Qualifier("rateSchemeCfgService")
	private RateSchemeCfgService rateSchemeCfgService;
	@Autowired
	@Qualifier("rateSchemeDetailService")
	private RateSchemeDetailService rateSchemeDetailService;
	@Autowired
	@Qualifier("contTempGService")
	private ContTempGService contTempGService;
	@Autowired
	@Qualifier("sRuleCollService")
	private SRuleCollService sRuleCollService;

	@Autowired
	@Qualifier("prdApplyRuleService")
	private PrdApplyRuleService prdApplyRuleService;
	@Autowired
	@Qualifier("prdChangeRecordService")
	private PrdChangeRecordService prdChangeRecordService;
	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;

	/**
	 * 列表数据查询(产品上线申请)
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/prd/info/applys", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PrdInfoApplyVO>> queryPrdInfoApplyAll(@RequestBody PrdInfoApplyVO vo) {
		vo.setReqType(ConsoleConstant.REQ_TYPE_01);
		// 根据用户角色获取用户权限方案
		List<PrdInfoApplyVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = prdInfoApplyService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = prdInfoApplyService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		}
		return getResponseData(outputVo);

	}

	/**
	 * 列表数据查询(产品变更申请)
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/prd/info/changeApplys", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PrdInfoApplyVO>> queryPrdInfoApplyAll2Change(@RequestBody PrdInfoApplyVO vo) {
		vo.setReqType(ConsoleConstant.REQ_TYPE_02);
		// 根据用户角色获取用户权限方案
		List<PrdInfoApplyVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = prdInfoApplyService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = prdInfoApplyService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		}
		KeyValue orgColumnMapping = new KeyValue("legalOrgCode", "legalOrgCodeName");
		this.displayNames(outputVo, null, orgColumnMapping);
		return getResponseData(outputVo);
	}

	/**
	 * 列表数据查询(产品下线申请)
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/prd/info/offlineApplys", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PrdInfoApplyVO>> queryPrdInfoApplyAll2Offline(@RequestBody PrdInfoApplyVO vo) {
		vo.setReqType(ConsoleConstant.REQ_TYPE_03);
		// 根据用户角色获取用户权限方案
		List<PrdInfoApplyVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = prdInfoApplyService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = prdInfoApplyService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		}
		KeyValue orgColumnMapping = new KeyValue("legalOrgCode", "legalOrgCodeName");
		this.displayNames(outputVo, null, orgColumnMapping);
		return getResponseData(outputVo);
	}

	/**
	 * 列表数据查询(产品停用申请)
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/prd/info/stopApplys", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PrdInfoApplyVO>> queryPrdInfoApplyAll2Stop(@RequestBody PrdInfoApplyVO vo) {
		vo.setReqType(ConsoleConstant.REQ_TYPE_04);
		// 根据用户角色获取用户权限方案
		List<PrdInfoApplyVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = prdInfoApplyService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = prdInfoApplyService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = prdInfoApplyService.queryAllOwner(vo);
			break;
		}
		KeyValue orgColumnMapping = new KeyValue("legalOrgCode", "legalOrgCodeName");
		this.displayNames(outputVo, null, orgColumnMapping);
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键查询详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/prd/info/apply/{bizSerno}", method = RequestMethod.GET)
	public @ResponseBody ResponseData<PrdInfoApplyVO> queryByPk(@PathVariable("bizSerno") String bizSerno) {
		PrdInfoApplyVO inVo = new PrdInfoApplyVO();
		inVo.setBizSerno(bizSerno);
		PrdInfoApplyVO outputVo = prdInfoApplyService.queryByPk(inVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键删除信息
	 * 
	 * @param prdInfoApply
	 * @return
	 */
	@RequestMapping(value = "/prd/info/apply", method = RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody PrdInfoApplyVO inPrdInfoApplyVo) {
		int outputVo = prdInfoApplyService.deleteByPk(inPrdInfoApplyVo);

		// 删除申请关联规则信息
		if (outputVo == 1) {
			PrdApplyRuleVO prdApplyRuleVo = new PrdApplyRuleVO();
			prdApplyRuleVo.setBizSerno(inPrdInfoApplyVo.getBizSerno());
			prdApplyRuleService.deleteByBizSerno(prdApplyRuleVo);
		}

		return getResponseData(outputVo);
	}

	/**
	 * 根据主键更新信息
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
	@RequestMapping(value = "/prd/info/apply", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody PrdInfoApplyVO inPrdInfoApplyVo) {
		int outputVo = prdInfoApplyService.updateByPk(inPrdInfoApplyVo);

		// 保存产品申请规则关联信息
		List<PrdApplyRuleVO> ruleData = inPrdInfoApplyVo.getRuleData();
		if (ruleData != null && ruleData.size() > 0) {
			for (int i = 0; i < ruleData.size(); i++) {
				PrdApplyRuleVO relVO = ruleData.get(i);
				relVO.setBizSerno(inPrdInfoApplyVo.getBizSerno());

				if (relVO != null) {
					if (StringUtils.isNotEmpty(relVO.getOpFlag())) {
						if (relVO.getOpFlag().equals(ConsoleConstant.CONSOLE_OPT_FLAG_ADD)) {
							// 新增
							prdApplyRuleService.insertPrdApplyRule(relVO);
						} else if (relVO.getOpFlag().equals(ConsoleConstant.CONSOLE_OPT_FLAG_DELETE)) {
							// 删除
							prdApplyRuleService.deleteByPk(relVO);
						} else {
							// 更新
							prdApplyRuleService.updateByPk(relVO);
						}
					} else {
						// 更新
						prdApplyRuleService.updateByPk(relVO);
					}
				}
			}
		}

		return getResponseData(outputVo);
	}

	/**
	 * 新增数据
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
	@RequestMapping(value = "/prd/info/apply", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertPrdInfoApply(@RequestBody PrdInfoApplyVO inPrdInfoApplyVo) {
		int outputVo = -1;
		// 先判断产品是否存在待发起申请
		String reqType = inPrdInfoApplyVo.getReqType();
		if (ConsoleConstant.REQ_TYPE_02.equals(reqType) || ConsoleConstant.REQ_TYPE_03.equals(reqType)
				|| ConsoleConstant.REQ_TYPE_04.equals(reqType)) {
			String prdId = inPrdInfoApplyVo.getPrdId();
			List<PrdInfoApplyVO> prdVo = prdInfoApplyService.queryChangingPrdByPrdId(prdId);
			if (prdVo != null && prdVo.size() > 0) {
				ResponseData<Integer> responseData = new ResponseData<Integer>();
				responseData.setMessage("该产品已存在待发起的变更、下线、停用申请！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
		}
		// 获取流水号
		String bizSerno = "";
		try {
			bizSerno = generateSerialNo();
		} catch (Exception e) {
			logger.debug("获取流水号失败!");
			return getResponseData(outputVo);
		}
		inPrdInfoApplyVo.setBizSerno(bizSerno);// 流水号
		inPrdInfoApplyVo.setAprvStatus(ConsoleConstant.APRV_STATUS_01);
		setUserInfoToVO(inPrdInfoApplyVo);
		outputVo = prdInfoApplyService.insertPrdInfoApply(inPrdInfoApplyVo);

		// 保存产品申请规则关联信息
		List<PrdApplyRuleVO> ruleData = inPrdInfoApplyVo.getRuleData();
		if (ruleData != null && ruleData.size() > 0) {
			for (int i = 0; i < ruleData.size(); i++) {
				PrdApplyRuleVO relVO = ruleData.get(i);
				relVO.setBizSerno(bizSerno);
				if (relVO != null) {
					prdApplyRuleService.insertPrdApplyRule(relVO);
				}
			}
		}

		return getResponseData(outputVo);

	}

	/**
	 * 复制产品
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
	@RequestMapping(value = "/prd/info/apply/copy", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> copyPrdInfoApply(@RequestBody PrdInfoApplyVO inPrdInfoApplyVo) {
		int outputVo = -1;
		inPrdInfoApplyVo = prdInfoApplyService.queryByPk(inPrdInfoApplyVo);
		PrdInfoApplyVO prdInfoApplyVo = new PrdInfoApplyVO();
		BeanUtility.beanCopy(inPrdInfoApplyVo, prdInfoApplyVo);
		// 获取流水号
		String bizSerno = "";
		try {
			bizSerno = generateSerialNo();
		} catch (Exception e) {
			logger.debug("获取流水号失败!");
			return getResponseData(outputVo);
		}
		prdInfoApplyVo.setBizSerno(bizSerno);// 流水号
		prdInfoApplyVo.setAprvStatus(ConsoleConstant.APRV_STATUS_01);// 审批状态
		prdInfoApplyVo.setAprvDate("");
		prdInfoApplyVo.setAprvUser("");
		setUserInfoToVO(prdInfoApplyVo);
		outputVo = prdInfoApplyService.insertPrdInfoApply(prdInfoApplyVo);

		// 保存产品申请规则关联信息
		PrdApplyRuleVO prdApplyRuleVo = new PrdApplyRuleVO();
		prdApplyRuleVo.setBizSerno(inPrdInfoApplyVo.getBizSerno());
		List<PrdApplyRuleVO> ruleData = prdApplyRuleService.queryAllByBizSerno(prdApplyRuleVo);
		if (ruleData != null && ruleData.size() > 0) {
			for (int i = 0; i < ruleData.size(); i++) {
				PrdApplyRuleVO relVO = ruleData.get(i);
				relVO.setBizSerno(bizSerno);
				if (relVO != null) {
					prdApplyRuleService.insertPrdApplyRule(relVO);
				}
			}
		}

		return getResponseData(outputVo);

	}

	/**
	 * 提交处理
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
//	@RequestMapping(value = "/prd/info/submitApply", method = RequestMethod.POST)
//	public @ResponseBody ResponseData<Integer> submitPrdInfoApply(@RequestBody PrdInfoApplyVO inPrdInfoApplyVo) {
//		int count = -1;
//		String bizSerno = "";
//		if (Objects.nonNull(inPrdInfoApplyVo)) {
//			bizSerno = inPrdInfoApplyVo.getBizSerno();
//			String reqType = inPrdInfoApplyVo.getReqType();
//			if (bizSerno == null || "".equals(bizSerno)) {
//				if (ConsoleConstant.REQ_TYPE_02.equals(reqType) || ConsoleConstant.REQ_TYPE_03.equals(reqType)
//						|| ConsoleConstant.REQ_TYPE_04.equals(reqType)) {
//					String prdId = inPrdInfoApplyVo.getPrdId();
//					List<PrdInfoApplyVO> prdVo = prdInfoApplyService.queryChangingPrdByPrdId(prdId);
//					if (prdVo != null && prdVo.size() > 0) {
//						ResponseData<Integer> responseData = new ResponseData<Integer>();
//						responseData.setMessage("该产品已存在待发起的变更、下线、停用申请！");
//						responseData.setCode(ApplicationConstance.FAILURE);
//						responseData.setSuccess(false);
//						return responseData;
//					}
//				}
//			}
//			// 提交时校验选择的合同模板、利率方案、电核问题、额度测算是否生效等
//			ResponseData<Integer> response = check(inPrdInfoApplyVo);
//			if (Objects.nonNull(response)) {
//				return response;
//			}
//			// 校验业务流程
//			count = 1;
//			String flowId = "";
//			UserInfo userInfo = getUserInfo();
//			String legalOrgCode = userInfo.getLegalOrg().getOrgCode();
//			BizFlowInfoVO bizFlowInfoVo = new BizFlowInfoVO();
//			bizFlowInfoVo.setLegalOrgCode(legalOrgCode);
//			bizFlowInfoVo.setBizFlowType(BaseConstant.BIZ_FLOW_TYPE_01);
//			List<BizFlowInfoVO> list = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVo);
//			if (Objects.nonNull(list) && list.size() > 0) {
//				bizFlowInfoVo = list.get(0);
//				flowId = bizFlowInfoVo.getBizFlowId();
//			} else {
//				// 若没有该法人机构配置则走省配置
//				bizFlowInfoVo.setLegalOrgCode(BaseConstant.LEGAL_ORG_CODE_00001);
//				list = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVo);
//				if (Objects.nonNull(list) && list.size() > 0) {
//					bizFlowInfoVo = list.get(0);
//					flowId = bizFlowInfoVo.getBizFlowId();
//				} else {
//					ResponseData<Integer> responseData = new ResponseData<Integer>();
//					responseData.setMessage("该法人机构未配置产品业务流转，提交失败！");
//					responseData.setCode(ApplicationConstance.FAILURE);
//					responseData.setSuccess(false);
//					return responseData;
//				}
//			}
//			inPrdInfoApplyVo.setAprvStatus(ConsoleConstant.APRV_STATUS_01);
//			// 产品上线：修改申请信息，插入产品；产品变更：修改申请信息，插入新产品，失效原产品；产品下线：修改申请信息，失效产品
//			PrdInfoApplyVO prdInfoApplyVO = this.insertOrUpdatePrdInfoApply(inPrdInfoApplyVo);
//			if (prdInfoApplyVO == null) {
//				ResponseData<Integer> responseData = new ResponseData<Integer>();
//				responseData.setMessage("提交失效！");
//				responseData.setCode(ApplicationConstance.FAILURE);
//				responseData.setSuccess(false);
//				return responseData;
//			} else {
//				String eventId = "";
//				if (ConsoleConstant.REQ_TYPE_01.equals(reqType)) {
//					eventId = "E000006";
//				} else if (ConsoleConstant.REQ_TYPE_02.equals(reqType)) {
//					eventId = "E000007";
//				} else if (ConsoleConstant.REQ_TYPE_03.equals(reqType)) {
//					eventId = "E000008";
//				} else if (ConsoleConstant.REQ_TYPE_04.equals(reqType)) {
//					eventId = "STOP_PRDINFO";
//				}
//				try {
//					EngineHttpRequestVO eVo = new EngineHttpRequestVO();
//					eVo.setBizLagelOrgCode(prdInfoApplyVO.getOrgCode());
//					eVo.setE_bizSerno(prdInfoApplyVO.getBizSerno());
//					eVo.setFlowId(flowId);
//					eVo.setEventId(eventId);
//					eVo.setG_bizSerno(prdInfoApplyVO.getPrdCode());
//					eVo.setData(prdInfoApplyVO);
//					HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
//					prdInfoApplyVO.setAprvStatus(ConsoleConstant.APRV_STATUS_02);
//					// 产品变更需要插入变更记录
//					if (ConsoleConstant.REQ_TYPE_02.equals(reqType)) {
//						// 先删除
//						PrdChangeRecordVO prdChangeRecordVo = new PrdChangeRecordVO();
//						prdChangeRecordVo.setBizSerno(prdInfoApplyVO.getBizSerno());
//						prdChangeRecordService.deleteByBizSerno(prdChangeRecordVo);
//						// 插入变更记录
//						prdInfoApplyService.insertPrdChangeRecords(prdInfoApplyVO);
//					}
//					// 更新申请表
//					count = prdInfoApplyService.updateByPk(prdInfoApplyVO);
//				} catch (Exception e) {
//					logger.info("保存成功，调用流程异常，提交失败！", e);
//					ResponseData<Integer> responseData = new ResponseData<Integer>();
//					responseData.setMessage("保存成功，调用流程异常，提交失败！");
//					responseData.setCode("-2");
//					responseData.setSuccess(false);
//					return responseData;
//				}
//			}
//
//		}
//		return getResponseData(count);
//	}

	/**
	 * 提交时校验选择的合同模板、利率方案、电核问题、额度测算是否生效等
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
	private ResponseData<Integer> check(PrdInfoApplyVO inPrdInfoApplyVo) {
		ResponseData<Integer> responseData = null;
		// 校验产品选择的利率方案
		String schemeNo = inPrdInfoApplyVo.getRateSchemeId();
		if (schemeNo != null && !"".equals(schemeNo)) {
			RateSchemeCfgVO rateSchemeCfgVO = new RateSchemeCfgVO();
			rateSchemeCfgVO.setSchemeNo(schemeNo);
			rateSchemeCfgVO = rateSchemeCfgService.queryByPk(rateSchemeCfgVO);
			if (Objects.isNull(rateSchemeCfgVO) || (Objects.nonNull(rateSchemeCfgVO) && rateSchemeCfgVO.getStatus() != null
					&& !ConsoleConstant.COMMON_STATUS_1.equals(rateSchemeCfgVO.getStatus()))) {
				responseData = new ResponseData<Integer>();
				responseData.setMessage("利率方案状态为非生效！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			} else if (rateSchemeCfgVO != null && !inPrdInfoApplyVo.getCreditTermUnit().equals(rateSchemeCfgVO.getSingleTermUnit())) {
				responseData = new ResponseData<Integer>();
				responseData.setMessage("产品期限单位与利率方案期限单位不匹配！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
			RateSchemeDetailVO rsdVO = new RateSchemeDetailVO();
			rsdVO.setSchemeNo(schemeNo);
			rsdVO.setTerm(inPrdInfoApplyVo.getCreditTerm() + "");
			rsdVO = rateSchemeDetailService.queryByschemeNoTerm(rsdVO);
			if (rsdVO == null) {
				responseData = new ResponseData<Integer>();
				responseData.setMessage("产品期限与利率方案配置不匹配！" + inPrdInfoApplyVo.getCreditTerm());
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
		}
		// 校验合同模板
		String contTemplateId = inPrdInfoApplyVo.getContTemplateId();
		ContTempGVO contTempGVo = new ContTempGVO();
		contTempGVo.setContGroupId(contTemplateId);
		contTempGVo = contTempGService.queryByPk(contTempGVo);
		if (Objects.isNull(contTempGVo) || (Objects.nonNull(contTempGVo) && contTempGVo.getStatus() != null
				&& !ConsoleConstant.COMMON_STATUS_1.equals(contTempGVo.getStatus()))) {
			responseData = new ResponseData<Integer>();
			responseData.setMessage("合同模板状态为非生效！");
			responseData.setCode(ApplicationConstance.FAILURE);
			responseData.setSuccess(false);
			return responseData;
		}
		// 校验电核问题
		String eleNucFormId = inPrdInfoApplyVo.getEleNucFormId();
		TelVerifGrpCfgVO telVerifGrpCfgVo = new TelVerifGrpCfgVO();
		telVerifGrpCfgVo.setTplGrpId(eleNucFormId);
		if (Objects.isNull(telVerifGrpCfgVo) || (Objects.nonNull(telVerifGrpCfgVo) && telVerifGrpCfgVo.getStatus() != null
				&& !ConsoleConstant.COMMON_STATUS_1.equals(telVerifGrpCfgVo.getStatus()))) {
			responseData = new ResponseData<Integer>();
			responseData.setMessage("电核组状态为非生效！");
			responseData.setCode(ApplicationConstance.FAILURE);
			responseData.setSuccess(false);
			return responseData;
		}
		// 校验额度测算
		String crdMeaMedolId = inPrdInfoApplyVo.getCrdMeaMedolId();
		SRuleCollVO sRuleCollVo = new SRuleCollVO();
		sRuleCollVo.setRuleCollId(crdMeaMedolId);
		sRuleCollVo = sRuleCollService.queryByPk(sRuleCollVo);
		if (Objects.isNull(sRuleCollVo) || (Objects.nonNull(sRuleCollVo) && sRuleCollVo.getStatus() != null
				&& !ConsoleConstant.COMMON_STATUS_1.equals(sRuleCollVo.getStatus()))) {
			responseData = new ResponseData<Integer>();
			responseData.setMessage("额度测算状态为非生效！");
			responseData.setCode(ApplicationConstance.FAILURE);
			responseData.setSuccess(false);
			return responseData;
		}
		return null;
	}

	/**
	 * 新增或修改申请信息
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
	private PrdInfoApplyVO insertOrUpdatePrdInfoApply(PrdInfoApplyVO inPrdInfoApplyVo) {
		@SuppressWarnings("unused")
		int count = -1;
		String bizSerno = "";
		if (Objects.nonNull(inPrdInfoApplyVo)) {
			bizSerno = inPrdInfoApplyVo.getBizSerno();
		}
		String reqType = inPrdInfoApplyVo.getReqType();
		// 产品上线，产品变更产生版本号
		if (ConsoleConstant.REQ_TYPE_01.equals(reqType)) {
			String prdVersion = "1";// 版本号
			inPrdInfoApplyVo.setPrdVersion(prdVersion);// 版本号
			/** 【注释】 */
			/**  try {
			 prdVersion = sequenceService.getSequence(SequenceConstance.PRD_VERSION, null,
			 null);
			 inPrdInfoApplyVo.setPrdVersion(prdVersion);//版本号
			 } catch (Exception e) {
			 logger.info("获取流水号失败!");
			 return null;
			 }*/
		}
		/** 【注释】 */
		/** else if(ConsoleConstant.REQ_TYPE_02.equals(reqType)) {
			String prdVersion = inPrdInfoApplyVo.getPrdVersion();//版本号
			int v = Integer.parseInt(prdVersion);
			v++;
			prdVersion = Integer.toString(v);
			inPrdInfoApplyVo.setPrdVersion(prdVersion);//版本号
		}
		inPrdInfoApplyVo.setAprvStatus(ConsoleConstant.APRV_STATUS_02);*/
		// 有流水号则更新数据，没有则新增数据
		inPrdInfoApplyVo.setOrgCode(getUserInfo().getOrgInfo().getOrgCode());
		if (bizSerno != null && !"".equals(bizSerno)) {
			// 更新申请表
			count = prdInfoApplyService.updateByPk(inPrdInfoApplyVo);
		} else {
			try {
				// 获取流水号
				bizSerno = generateSerialNo();;
			} catch (Exception e) {
				logger.debug("获取流水号失败!");
				return null;
			}
			inPrdInfoApplyVo.setBizSerno(bizSerno);// 流水号
			setUserInfoToVO(inPrdInfoApplyVo);
			// 插入申请表
			count = prdInfoApplyService.insertPrdInfoApply(inPrdInfoApplyVo);
		}

		// 保存产品申请规则关联信息
		List<PrdApplyRuleVO> ruleData = inPrdInfoApplyVo.getRuleData();
		if (ruleData != null && ruleData.size() > 0) {
			for (int i = 0; i < ruleData.size(); i++) {
				PrdApplyRuleVO relVO = ruleData.get(i);
				relVO.setBizSerno(inPrdInfoApplyVo.getBizSerno());

				if (relVO != null) {
					if (StringUtils.isNotEmpty(relVO.getOpFlag())) {
						if (relVO.getOpFlag().equals(ConsoleConstant.CONSOLE_OPT_FLAG_ADD)) {
							// 新增
							prdApplyRuleService.insertPrdApplyRule(relVO);
						} else if (relVO.getOpFlag().equals(ConsoleConstant.CONSOLE_OPT_FLAG_DELETE)) {
							// 删除
							prdApplyRuleService.deleteByPk(relVO);
						} else {
							// 更新
							prdApplyRuleService.updateByPk(relVO);
						}
					} else {
						// 更新
						prdApplyRuleService.updateByPk(relVO);
					}
				}
			}
		}

		return inPrdInfoApplyVo;
	}
	
	/**
	 * 新增新版本产品信息，修改原产品信息状态(产品上线：插入产品；产品变更：插入新产品，失效原产品；产品下线：失效产品)
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 * 
	 * private int insertOrUpdatePrdInfo(PrdInfoApplyVO inPrdInfoApplyVo)
	 */

	/**
	 * 产品变动历史列表数据查询
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/prd/info/applyDetails", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PrdInfoApplyVO>> queryPrdInfoApplyDetails(@RequestBody PrdInfoApplyVO vo) {
		List<PrdInfoApplyVO> outputVo = prdInfoApplyService.queryPrdInfoApplyDetails(vo);
		KeyValue orgColumnMapping = new KeyValue("legalOrgCode", "legalOrgCodeName");
		this.displayNames(outputVo, null, orgColumnMapping);
		return getResponseData(outputVo);

	}
	
	private String generateSerialNo() throws Exception {
		PatternedLimitableSeqService sequenceService = 
				SpringContextUtils.getBean(PatternedLimitableSeqService.class);
		return sequenceService.getPatternedSequence(SequenceConstance.PRD_INFO_APPLY_SEQ_ID, 
				SequenceConstance.PRD_INFO_APPLY_SEQ_PATTERN, 5);
	}
}
